package artid.com.arttogo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.VolleyError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.bean.SearchRequestBean;
import artid.com.arttogo.bean.SearchRequestBeanSend;
import artid.com.arttogo.bean.SelectphraseParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.VeDate;

public class CollecterSearchActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {
	/**
	 * 顶部搜索
	 */
	private ImageView back;
	ImageView mimgMirrorCenter, mimgMirrorLeft;
	EditText meditSearch;
	View viewSearch;
	TextView textSearchTag, textcancel;
	Boolean isSearching = false;
	LinearLayout linearSearch;
	private int anmiSpeed = 400;
	View titleSearch;
	String searchWord = "";

	String name = "";
	String id = "";
	LinearLayout mMainLinearLayout;
	String resultMain = "";
	private Button confirmBtn;
	private Button clearBtn;
	private List<SearchRequestBean> list_search;// 搜索数据
	ArrayList<View> listTags;
	List<SelectphraseParser> mainVd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_collecter_search);
		mContext = CollecterSearchActivity.this;
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		list_search = new ArrayList<SearchRequestBean>();
		mMainLinearLayout = (LinearLayout) findViewById(R.id.search_main);
		meditSearch = (EditText) findViewById(R.id.editText1);
		titleSearch = (View) findViewById(R.id.collecter_serach);
		textcancel = (TextView) findViewById(R.id.searchcancel);
		textcancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		// titleSearch.setOnClickListener(searchlistener());
		back = (ImageView) findViewById(R.id.title_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		clearBtn = (Button) findViewById(R.id.clt_srh_clear);
		clearBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 清空条件
				mMainLinearLayout.removeAllViews();
				resultMain = "";
				if (list_search != null) {
					list_search.clear();
				}
				setdata(mainVd);
			}
		});
		confirmBtn = (Button) findViewById(R.id.clt_srh_confirm);
		confirmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				List<SearchRequestBeanSend> listsend = new ArrayList<SearchRequestBeanSend>();
				// 确定按钮
				for (int i = 0; i < list_search.size(); i++) {
					SearchRequestBeanSend item = new SearchRequestBeanSend();
					item.setName(list_search.get(i).getName());
					item.setType(list_search.get(i).getType());
					listsend.add(item);
				}
				Intent i = new Intent(mContext, SearchResults_Activity.class);
				i.putExtra("list_search", (Serializable) listsend);
				String key = "";
				if (!TextUtils.isEmpty(meditSearch.getText().toString())) {
					key = meditSearch.getText().toString();
				}
				i.putExtra("keyword",key);
				startActivity(i);
			}
		});
		if(TextUtils.isEmpty(MySharedPreferences.getMySharedPreferences(mContext).getValue("CollecterSearchData", ""))){
			getData();
		}else{
			String JsonStr=MySharedPreferences.getMySharedPreferences(mContext).getValue("CollecterSearchData", "");
			List<SelectphraseParser> item = new ArrayList<SelectphraseParser>();
			try {
				JSONObject ob = new JSONObject(JsonStr);
				JSONArray arr = ob.optJSONArray("data");
				for (int i = 0; i < arr.length(); i++) {
					SelectphraseParser sp = new SelectphraseParser();
					sp.parse(arr.getJSONObject(i));
					item.add(sp);
				}
				setdata(item);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	private void getData() {
		VolleyBasic.getInstance((Activity) mContext).post(Cache.selectphrase,
				new HashMap<String, String>(), SelectphraseParser.class,
				new VolleyCallback() {

			@SuppressLint("NewApi")
			@Override
			public void onSuccess(VolleyData vd) {
				//保存Json串
				MySharedPreferences.getMySharedPreferences(mContext).setValue("CollecterSearchData", vd.getJson());
				setdata((List<SelectphraseParser>) vd.getList());
			}

			@Override
			public void onError(VolleyError volleyError) {
				// TODO Auto-generated method stub

			}
		});

	}

	@SuppressLint("NewApi") void setdata(List<SelectphraseParser> item) {
		mainVd = item;
		// TODO Auto-generated method stub

		for (int i = 0; i < item.size(); i++) {
			SelectphraseParser stp = item.get(i);
			String tag = stp.getSp_name();
			LinearLayout mLinear, mChild;
			mLinear = new LinearLayout(mContext);
			mLinear.setOrientation(LinearLayout.VERTICAL);
			mChild = new LinearLayout(mContext);
			mChild.setGravity(LinearLayout.HORIZONTAL);
			TextView title = new TextView(mContext);
			final String spname = item.get(i).getSp_name();
			final String field_value = item.get(i).getSp_field_value();
			title.setText(spname);
			title.setTextColor(Color.BLACK);
			title.setTextSize(18);
			android.widget.LinearLayout.LayoutParams titleParams = new LayoutParams(
					NetUtils.dip2px(mContext, title.getText().toString()
							.length() * 20), NetUtils.dip2px(mContext, 30));
			if (i == 0) {
				titleParams.setMargins(NetUtils.dip2px(mContext, 15),
						NetUtils.dip2px(mContext, 10),
						NetUtils.dip2px(mContext, 20), 0);
			} else {
				titleParams.setMargins(NetUtils.dip2px(mContext, 15),
						NetUtils.dip2px(mContext, 40),
						NetUtils.dip2px(mContext, 20), 0);
			}

			title.setLayoutParams(titleParams);
			mLinear.addView(title);

			int count = 0;
			for (int j = 0; j < stp.getList().size(); j++) {
				final String wordtag = stp.getList().get(j).getSp_value_name();
				TextView t1 = new TextView(mContext);
				t1.setBackground(ContextCompat.getDrawable(mContext,
						R.drawable.frame_black_stoke));
				android.widget.LinearLayout.LayoutParams layoutParams = new LayoutParams(
						NetUtils.dip2px(mContext, wordtag.length() * 16 + 10),
						NetUtils.dip2px(mContext, 30));
				layoutParams.setMargins(NetUtils.dip2px(mContext, 20),
						NetUtils.dip2px(mContext, 20), 0, 0);
				t1.setLayoutParams(layoutParams);
				t1.setGravity(Gravity.CENTER);
				t1.setTextColor(Color.BLACK);
				t1.setText(wordtag);
				t1.setOnClickListener(new OnClickListener() {

					@SuppressLint("NewApi") @Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						String resultStr = spname + ":" + wordtag + "#";
						if (!resultMain.contains(resultStr)) {
							// 同一大类下是否有重复
							if (!resultMain.contains(spname)) {
								// 单选判断
								resultMain = resultMain + resultStr;
								arg0.setBackground(ContextCompat.getDrawable(
										mContext, R.drawable.frame_gray_solid));
								// 将选择的搜索值加入集合
								SearchRequestBean bean = new SearchRequestBean();
								bean.setType(field_value);
								bean.setName(wordtag);
								bean.setView(arg0);
								list_search.add(bean);
							} else {
								List<SearchRequestBean> listOld = list_search;
								for (int k = 0; k < list_search.size(); k++) {
									SearchRequestBean bean = list_search.get(k);
									if (bean.getType().equals(field_value)) {
										View view = bean.getView();
										view.setBackground(ContextCompat
												.getDrawable(
														mContext,
														R.drawable.frame_black_stoke));
										listOld.remove(k);
									}
								}
								list_search = listOld;
								String deltOld = resultMain
										.substring(resultMain.indexOf(spname));
								deltOld = deltOld.substring(0,
										deltOld.indexOf("#") + 1);
								resultMain = resultMain.replace(deltOld, "");

								//
								// 添加新的
								resultMain = resultMain + resultStr;
								arg0.setBackground(ContextCompat.getDrawable(
										mContext, R.drawable.frame_gray_solid));
								// 将选择的搜索值加入集合
								SearchRequestBean bean = new SearchRequestBean();
								bean.setType(field_value);
								bean.setName(wordtag);
								bean.setView(arg0);
								list_search.add(bean);

							}
						} else {
							// 单击View清空所选择的状态
							resultMain = resultMain.replace(resultStr, "");
							arg0.setBackground(ContextCompat.getDrawable(
									mContext, R.drawable.frame_black_stoke));
							if (list_search != null && list_search.size() != 0) {
								for (int k = 0; k < list_search.size(); k++) {
									if (wordtag.equals(list_search.get(k)
											.getName())) {
										list_search.remove(k);

									}
								}
							}
						}
					}
				});
				mChild.addView(t1);
				count += wordtag.length();
				if (count > 9 || (j == stp.getList().size() - 1 && count < 10)) {
					count = 0;
					mLinear.addView(mChild);
					mChild = new LinearLayout(mContext);
					mChild.setGravity(LinearLayout.HORIZONTAL);
				}

			}
			mMainLinearLayout.addView(mLinear);

		}

		//
		//		openInput();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public void onClick(View v) {

	}

	void startSearch() {
		getData();

		Animation translateAnimation2 = new TranslateAnimation(VeDate.dip2px(
				mContext, 160), 0f, 0f, 0f);
		translateAnimation2.setDuration(anmiSpeed);
		mimgMirrorLeft.setAnimation(translateAnimation2);
		mimgMirrorLeft.setVisibility(View.VISIBLE);
		mimgMirrorCenter.setVisibility(View.GONE);
		textSearchTag.setVisibility(View.GONE);
		Animation scaleAnimation = new ScaleAnimation(1f, 0.8f, 1f, 1f, 1f, 1f);
		scaleAnimation.setDuration(anmiSpeed);
		scaleAnimation.setFillAfter(true);
		scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub
				meditSearch.setVisibility(View.VISIBLE);
				textcancel.setVisibility(View.VISIBLE);
				meditSearch.requestFocus();

				openInput();

			}
		});
		linearSearch.setAnimation(scaleAnimation);
	}

	// OnClickListener searchlistener(){
	// return new OnClickListener() {
	//
	// @Override
	// public void onClick(View arg0) {
	// // TODO Auto-generated method stub
	// switch (arg0.getId()) {
	// case R.id.relasearch:
	// getData();
	// if (!isSearching) {
	// isSearching = true;
	// Animation translateAnimation2 = new TranslateAnimation(
	// VeDate.dip2px(mContext, 160), 0f, 0f, 0f);
	// translateAnimation2.setDuration(anmiSpeed);
	// mimgMirrorLeft.setAnimation(translateAnimation2);
	// mimgMirrorLeft.setVisibility(View.VISIBLE);
	// mimgMirrorCenter.setVisibility(View.GONE);
	// textSearchTag.setVisibility(View.GONE);
	// Animation scaleAnimation = new ScaleAnimation(1f, 0.8f, 1f, 1f,
	// 1f, 1f);
	// scaleAnimation.setDuration(anmiSpeed);
	// scaleAnimation.setFillAfter(true);
	// scaleAnimation
	// .setAnimationListener(new Animation.AnimationListener() {
	// @Override
	// public void onAnimationStart(Animation arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onAnimationRepeat(Animation arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onAnimationEnd(Animation arg0) {
	// // TODO Auto-generated method stub
	// meditSearch.setVisibility(View.VISIBLE);
	// textcancel.setVisibility(View.VISIBLE);
	// meditSearch.requestFocus();
	//
	// openInput();
	//
	// }
	// });
	// linearSearch.setAnimation(scaleAnimation);
	//
	// }
	// break;
	//
	// case R.id.searchcancel:
	// finish();
	// // if (isSearching) {
	// // isSearching = false;
	// // // Animation translateAnimation2 = new
	// // // TranslateAnimation(0f,VeDate.dip2px(getActivity(), 160),
	// // // 0f, 0f);
	// // // translateAnimation2.setDuration(500);
	// // // mimgMirrorLeft.setAnimation(translateAnimation2);
	// // mimgMirrorCenter.setVisibility(View.GONE);
	// // mimgMirrorLeft.setVisibility(View.GONE);
	// // meditSearch.setText("");
	// // meditSearch.setVisibility(View.GONE);
	// // textSearchTag.setVisibility(View.VISIBLE);
	// // Animation scaleAnimation = new ScaleAnimation(0.8f, 1f, 1f, 1f,
	// // 1f, 1f);
	// // scaleAnimation.setDuration(500);
	// // scaleAnimation.setFillAfter(true);
	// // linearSearch.setAnimation(scaleAnimation);
	// // textcancel.setVisibility(View.GONE);
	// //
	// // viewSearch.setVisibility(View.GONE);
	// // }
	// break;
	//
	// case R.id.collecter_serach:
	// viewSearch.setVisibility(View.VISIBLE);
	// onClick(viewSearch);
	// break;
	// default:
	// break;
	// }
	// }
	// };
	// }
	void openInput() {
		InputMethodManager m = (InputMethodManager) meditSearch.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	// void setSearchAnim() {
	// textcancel = (TextView) findViewById(R.id.searchcancel);
	// // textcancel.setOnClickListener(searchlistener());
	// textcancel.setVisibility(View.GONE);
	// linearSearch = (LinearLayout) findViewById(R.id.linearLayout1);
	// textSearchTag = (TextView) findViewById(R.id.textsearch);
	// viewSearch = (View) findViewById(R.id.relasearch);
	// // viewSearch.setOnClickListener(searchlistener());
	// mimgMirrorCenter = (ImageView) findViewById(R.id.imageView1);
	// mimgMirrorLeft = (ImageView) findViewById(R.id.imageView2);
	// meditSearch = (EditText) findViewById(R.id.editText1);
	// meditSearch.setVisibility(View.GONE);
	// meditSearch
	// .setOnEditorActionListener(new TextView.OnEditorActionListener() {
	// public boolean onEditorAction(TextView v, int actionId,
	// KeyEvent event) {
	// if (actionId == EditorInfo.IME_ACTION_SEARCH
	// || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
	// ///
	// return true;
	// }
	// return false;
	// }
	// });
	// mimgMirrorLeft.setVisibility(View.GONE);
	// }

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}
}
